package cn.yj.alipay.service;

import cn.yj.alipay.config.AliPayConfig;
import cn.yj.common.interfaces.ISign;
import cn.yj.tools.exception.ServiceException;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author 永健
 * @since 2022-02-19 14:22
 */
public class AlipaySign implements ISign, ApplicationContextAware {

    @Resource
    private AliPayConfig alipayConfig;


    private static ApplicationContext app;

    public static AlipaySign getInstance() {
        if (app == null) {
            throw new ServiceException("未启用支付宝支付");
        }
        return app.getBean(AlipaySign.class);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        app = applicationContext;
    }

    @Override
    public boolean decryptSign(Map<String, String> params) {
        try {
            // 官方文档说要去除 sign 和 sign_type 字段，但是它的sdk中只去除了 sign
            params.remove("sign_type");
            return AlipaySignature.certVerifyV2(params, alipayConfig.getAlipayCertPath(), alipayConfig.getCharset(),
                    alipayConfig.getSignType());
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new ServiceException(e.getErrMsg());
        }
    }
}
